<?php

namespace App\Models;


use App\Http\Common\Lib\Common;

class Role extends BaseModel
{
	//
	public $timestamps = false;

	protected $validatorName = 'Role';

	/**
	 * 角色的权限
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function menus()
	{
		return $this->belongsToMany('App\Models\Menu', 'role_menu_relations', 'role_id', 'menu_id');
	}

	/**
	 * 角色列表
	 * @param int $parentId
	 * @param array $where
	 * @param bool $needSub
	 * @param array $lists
	 * @return array
	 */
	public function getList($parentId = 0, $where = [], $needSub = true, &$lists = [])
	{
		$res = $this->where('parent_id', $parentId)
			->where(function ($query) use ($where) {
				if (!empty($where)) {
					$query->where($where);
				}
			})->get();
		if ($res) {
			foreach ($res as $key => $value) {
				//array_push($lists,$res);
				$lists[] = $value;
				if ($needSub) {
					$this->getList($value->id, $where, $needSub, $lists);
				}
			}
		}
		return $lists;
	}

	/**
	 * 树状图
	 * @param int $parentId
	 * @param array $where
	 * @param bool $needSub
	 * @param array $checkedIds
	 * @return array
	 */
	public function treeList($parentId = 0, $where = [], $needSub = true, $checkedIds = [])
	{
		$list = [];
		$res = $this->where('parent_id', $parentId)
			->where(function ($query) use ($where) {
				if (!empty($where)) {
					$query->where($where);
				}
			})->get();
		if ($res) {
			foreach ($res as $key => $value) {
				$item = [
					'id' => $value->id,
					'label' => $value->name,
				];
				if (in_array($value->id, $checkedIds)) {
					$item['checked'] = true;
				}
				if ($needSub) {
					$subs = $this->treeList($value->id, $where, $needSub, $checkedIds);
					if ($subs) {
						$item['children'] = $subs;
					}
				}
				$list[] = $item;
			}
		}
		return $list;
	}

	/**
	 * 保存角色权限设置
	 * @param $id
	 * @param array $roleIds
	 * @return array
	 */
	public function saveMenus($id, $menuIds = [])
	{
		$info = $this->findOne($id);
		if ($info['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($info['status'], $info['msg']);
		}
		$role = $info['data'];
		if (empty($menuIds)) {
			$role->menus()->detach();
		} else {
			$menuIds = array_map('intval', $menuIds);
			$oldMenus = $role->menus;
			$menuModel = new Menu();
			$newMenus = $menuModel->whereIn('id', $menuIds)->get();
			$removeMenus = $oldMenus->diff($newMenus);//需要移除的权限
			$addMenus = $newMenus->diff($oldMenus);//需要新增的权限
			$removeMenuIds = $removeMenus->pluck('id')->toArray();
			$addMenuIds = $addMenus->pluck('id')->toArray();

			if ($removeMenuIds) {
				$role->menus()->detach($removeMenuIds);
			}
			if ($addMenuIds) {
				$role->menus()->attach($addMenuIds);
			}
		}
		return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'));
	}

	/**
	 * 列表，主要用于下拉列表
	 * @param int $parentId
	 * @param bool $needSub
	 * @param int $loop
	 * @param array $lists
	 * @return array
	 */
	public function selectList($parentId = 0, $needSub = true, $loop = 0, &$lists = [])
	{
		$res = $this->where('parent_id', $parentId)
			->where('status', 1)
			->select(['id', 'name'])
			->get();
		if ($res) {
			foreach ($res as $key => $value) {
				$value->name = str_repeat('&nbsp;&nbsp;', $loop) . $value->name;
				$lists[] = $value;
				if ($needSub) {
					$this->selectList($value->id, $needSub, $loop + 1, $lists);
				}
			}
		}
		return $lists;
	}

	public function add($input)
	{
		$validateRes = $this->validateData($input, 'add');
		if ($validateRes['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($validateRes['status'], $validateRes['msg']);
		}
		$isUnique = $this->checkUnique('name', $input['name'], [['status', '>', '-1']]);
		if (!$isUnique) {
			return Common::dataFormat(config('statusInfo.status.repeated'), '该标签已存在');
		}
		$id = $this->insertGetId($input);
		if ($id) {
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'), [$this->primaryKey => $id]);
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}

	public function edit($input)
	{
		$validateRes = $this->validateData($input, 'edit');
		if ($validateRes['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($validateRes['status'], $validateRes['msg']);
		}
		$isUnique = $this->checkUnique('name', $input['name'], [['status', '>', '-1'], ['id', '<>', $input['id']]]);
		if (!$isUnique) {
			return Common::dataFormat(config('statusInfo.status.repeated'), '该标签已存在');
		}
		$tag = $this->where($this->primaryKey, $input[$this->primaryKey])->where('status', '>', -1)->first();
		if (!$tag) {
			return Common::dataFormat(config('statusInfo.status.notFound'), config('statusInfo.msg.notFound'));
		}
		$subIds = $this->getSubIds($input[$this->primaryKey], [['status', '>', -1]]);
		$subIds[] = $input[$this->primaryKey];
		if (in_array($input['parent_id'], $subIds)) {
			return Common::dataFormat(config('statusInfo.status.fail'), '父级分类不知能是自身或者自身的下级分类');
		}
		$res = $this->where($this->primaryKey, $input[$this->primaryKey])->update($input);
		if ($res) {
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'));
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}
}
